package br.com.example.carona;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

public class MaskHour {

	public static String unmask(String s) {
		return s.replaceAll("[.]", "").replaceAll("[-]", "")
				.replaceAll("[/]", "").replaceAll("[(]", "")
				.replaceAll("[)]", "").replaceAll("[:]", "");
	}

	public static TextWatcher insert(final String mask, final EditText ediTxt) {
		return new TextWatcher() {
			boolean isUpdating = true, finish = false;
			int controle = 0;

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				if (isUpdating) {
					controle++;
				}

				if (controle == 3 && isUpdating == true) {
					String old2 = ediTxt.getText().toString();
					String old = MaskHour.unmask(old2);
					String parte1 = old.substring(0, 2);
					String parte2 = old.substring(2, 3);
					String novo = parte1 + ":" + parte2;
					isUpdating = false;
					ediTxt.setText(novo);
					return;
				} else if (controle >= 4 && isUpdating == true) {
					String old2 = ediTxt.getText().toString();
					String old = MaskHour.unmask(old2);
					String parte1 = old.substring(0, 2);
					String parte2 = old.substring(2, 4);
					String novo = parte1 + ":" + parte2;
					isUpdating = false;
					finish = true;
					ediTxt.setText(novo);

					return;
				} else {
				}

				if (finish == false) {
					isUpdating = true;
				}

			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
				// controle = 0;
			}

		};
	}

}
